<template>
  <div class="update-photo">
    <img :src="img" alt class="img" ref="img" />
    <div class="toolbar">
      <div @click="$emit('close')" class="cancel">取消</div>
      <div @click="onConfirm" class="confirm">确定</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';

import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  }, methods: {
    onConfirm () {
      this.$toast.loading({
        message: '保存中',
        forbidClick: true,
        duration: 0
      })
      // 基于服务端的裁切使用gedata方法获取参数


      // 纯客户端的裁切使用getCroppedCanvas() 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {

        // 如果接口要求Content_type 时 application/json
        // 则传递普通Java 对象
        // await updateUserPhoto({
        //   photo:blob
        // })

        // 如果接口要求Content-Type 时multipart/form-data
        // 则你必须传递Formdata对象
        try {
          const formData = new FormData()

          formData.append('photo', blob)

          const { data: res } = await updateUserPhoto(formData)

          console.log(res);

          // 关闭弹出层
          this.$emit('close')
          // 更新视图
          this.$emit('update-photo', res.data.pthoto)
          this.$toast.success('更新成功')
        } catch (err) {
          this.$toast.fail('更新失败 ')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  background: black;
  height: 100%;
  .toolbar {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>